from question.models import Question
import json
from django.http import JsonResponse
from course.models import Member


# Create your views here.
def get_subject_list(request):
    subjects = Question.objects.filter().values_list(
        "question_chapter", flat=True
    )
    subject_list = set(list(subjects))
    return JsonResponse(
        {
            "result": True,
            "message": "获取成功",
            "code": 200,
            "data": list(subject_list)
        },
        json_dumps_params={"ensure_ascii": False},
    )


def get_choice(request):
    # 从requset中得到题的总数与类型
    # flag = request.GET.get('flag')
    # num = int(request.GET.get('num'))

    user_id = request.GET.get('user_id')
    flag = '1'
    num = 2

    total_qusertion = Coption.objects.all().count()

    questions = []
    cids = []
    for i in range(0, num):
        question = {}

        cid = 'C' + str(ceil(random.random() * total_qusertion))
        coption = Coption.objects.filter(cid=cid)

        cids.append(cid)
        question['title'] = coption.values()[0].get('ccontent')
        # question['answer'] = [CoptionAnswer.objects.filter(cid=cid).values()[0].get('answer')]
        options = [coption.values()[0].get(i) for i in ['coA', 'coB', 'coC', 'coD']]
        question['options'] = [
            {'code': 'A', 'option': options[0]},
            {'code': 'B', 'option': options[1]},
            {'code': 'C', 'option': options[2]},
            {'code': 'D', 'option': options[3]},
        ]

        questions.append(question)

    data = {
        'result': True,
        'data': {
            'user_id': '1',
            'titles': questions,
            'cids': cids,
            'user_id': user_id,
        }
    }

    return JsonResponse(data)


@login_exempt
def judge_question(request):
    # 从请求头中得到
    user_id = request.GET.get('user_id')
    cids = json.loads(request.GET.get('cids'))
    choices = json.loads(request.GET.get('selects'))

    length = len(cids)
    wrong_number = 0

    questions = []
    try:
        for i in range(0, length):
            question = {}
            q = Coption.objects.filter(cid=cids[i])

            question['title'] = q.values()[0].get('ccontent')

            options = [q.values()[0].get(s) for s in ['coA', 'coB', 'coC', 'coD']]
            question['options'] = [
                {'code': 'A', 'option': options[0]},
                {'code': 'B', 'option': options[1]},
                {'code': 'C', 'option': options[2]},
                {'code': 'D', 'option': options[3]}
            ]
            # options.append([q.values()[0].get(s) for s in ['coA', 'coB', 'coC', 'coD']])
            a = CoptionAnswer.objects.filter(cid=cids[i]).values()[0].get('answer')
            question['answer'] = a
            question['selects'] = choices[i]
            if choices[i] == a:
                question['T_or_F'] = True
            else:
                wrong_number = wrong_number + 1
                question['T_or_F'] = False
                # 记录用户id与错题的cid
                ErrorQuestion.objects.create(user_id=user_id, question_id=cids[i])
            questions.append(question)

        # 记录用户的正确题数与错误题数，以及做题时间
        User_log.objects.create(
            user_id=user_id,
            right_number=length-wrong_number,
            wrong_number=wrong_number,
            # time=str(datetime.datetime.now())
            time=str(timezone.now())
         )

    except Exception as e:
        data = {
            'result': False,
            'message': e,
        }

        return JsonResponse(data)

    data = {
        'result': True,
        'data': {
            'titles': questions,
        }
    }

    return JsonResponse(data)